<template>
  <div >
    <el-upload
      :show-file-list="false"
      :on-success="successUpload"
      :on-error="hanldeUploadError"
      :before-upload="beforeUpload"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :accept="accept"
      class="avatar-uploader">
      <el-row v-loading="form.loading">
        <small-image v-if="fileUrl" :url="fileUrl" :width="178" :height="178" class="avatar"/>
        <i v-else class="el-icon-plus avatar-uploader-icon"/>
      </el-row>
      <div slot="tip" class="el-upload__tip">
        <el-button v-show="fileUrl" size="small" type="danger" @click="removeFile">删除图片</el-button>
      </div>
    </el-upload>

  </div>
</template>

<script>

import { getToken } from '@/utils/auth'
import fileApi from '@/api/sys/file'
import miment from 'miment'
import endWith from 'licia/endWith'
import uuid from 'licia/uuid'

export default {
  props: {
    fileUrl: {
      type: String,
      default: ''
    },
    filePath: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: 'image/*'
    }
  },
  data() {
    return {
      form: {
        loading: false
      },
      ossClient: null
    }
  },
  computed: {
    uploadUrl: function() {
      return process.env.BASE_API + '/sapi/sys/file/upload'
    },
    uploadHeaders: function() {
      var headers = {}
      headers['sapi-token'] = getToken()
      return headers
    },
    finImageUrl: function() {
      if (!this.fileUrl) {
        return this.fileUrl
      }
      if (endWith(this.fileUrl, 'jpg') || endWith(this.fileUrl, 'jpeg') || endWith(this.fileUrl, 'png')) {
        return this.fileUrl + '?x-oss-process=image/resize,w_200,h_200'
      }
      return this.fileUrl
    }
  },
  mounted() {

  },
  methods: {
    // 上传成功
    successUpload(response, file, fileList) {
      if (response.code === 200) {
        this.$emit('update:fileUrl', response.data.fileUrl)
        this.$emit('update:filePath', response.data.filePath)
      }
      this.form.loading = false
    },
    removeFile() {
      this.$emit('update:fileUrl', null)
      this.$emit('update:filePath', null)
    },
    beforeUpload() {
      this.form.loading = true
    },
    hanldeUploadError() {
      this.form.loading = false
    }
  }
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
